package leetcode_600;

/**
 *@author 周杨
 *Minesweeper_529 扫雷游戏 
 *describe:深度优先搜索  AC 90%
 *2018年9月11日 上午10:46:34
 */
public class Minesweeper_529 {
	char [][]board;
	int row;
	int col;
	public char[][] updateBoard(char[][] board, int[] click) {
        this.board=board;
        this.row=board.length;
        this.col=board[0].length;
        dfs(click[0],click[1]);
        return this.board;
    }
	
	public void dfs(int x,int y) {
		if(x<0||x==row||y<0||y>col)
			return ;
		char now=this.board[x][y];
		if(now=='M') {
			this.board[x][y]='X';
			return ;
		}
		else if(now=='E') {
			int det=detect(x, y);
			if(det==0) {//是白板  必须延伸 延伸是在3X3数组里延伸
				this.board[x][y]='B';
				dfs(x+1,y);
				dfs(x,y+1);
				dfs(x-1,y);
				dfs(x,y-1);
				dfs(x+1,y+1);
				dfs(x+1,y-1);
				dfs(x-1,y+1);
				dfs(x-1,y-1);
			}
			else {
				this.board[x][y]=(char) ('0'+det);
			}
		}
	}
	
	public int detect(int x,int y) {
		int res=0;
		res+=judge(x-1, y);
		res+=judge(x+1, y);
		res+=judge(x, y-1);
		res+=judge(x, y+1);
		res+=judge(x-1, y-1);
		res+=judge(x-1, y+1);
		res+=judge(x+1, y-1);
		res+=judge(x+1, y+1);
		return res;
	}
	
	public int judge(int x,int y) {
		if(x<0||x==this.row||y<0||y==this.col)
			return 0;
		if(this.board[x][y]=='M')
			return 1;
		return 0;
	}
}
